

-- 函数 get_max_pkey_value 得到表字段的最大值
create or replace function get_max_pkey_value_f(
  v_schema      varchar(64),
  v_table       varchar(64),
  v_column_name varchar(64)
) returns int8
as $$
declare
  v_count int8;
  v_sql text;
begin
  if (v_schema is null or v_schema = '' or 
      v_table is null or v_table = '' or 
      v_column_name is null or v_column_name = '') then 
    return null::int8;
  else 
    v_sql := concat('select COALESCE(max(',v_column_name,'),0) from ',v_schema,'.',v_table);
    execute v_sql into v_count;
    return v_count;
  end if;
EXCEPTION
  WHEN OTHERS THEN
      -- 当发生任何未捕获的异常时执行此处的代码
      RAISE NOTICE 'An error occurred: %', SQLERRM;
      -- 可以选择性地重新抛出异常以回滚事务
      return null::int8;
end;
$$ language plpgsql;

-- select get_max_pkey_value_f(CURRENT_SCHEMA::varchar,'tzq_plan_log_t','log_ig');



